package com.hutao.manage.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.hutao.manage.component.MyConfig;
import com.hutao.manage.datasource.TargetDataSource;
import com.hutao.manage.mapper.BaseInfoMapper;
import com.hutao.manage.mapper.CitizensInfoMapper;
import com.hutao.manage.mapper.FirstLevelMedicalMapper;
import com.hutao.manage.mapper.HospNoteBasicJsonMapper;
import com.hutao.manage.mapper.HospNoteVersionMapper;
import com.hutao.manage.mapper.HospitalNoteVersionMapper;
import com.hutao.manage.mapper.HospitalizationNoteMapper;
import com.hutao.manage.mapper.MedicalResourceMapper;
import com.hutao.manage.mapper.MedicalResourcePicMapper;
import com.hutao.manage.mapper.ScanFileMapper;
import com.hutao.manage.mapper.TreatmentTraceMapper;
import com.hutao.manage.mapper.UploadScanFileMapper;
import com.hutao.manage.mapper.UploadScanMapper;
import com.hutao.manage.model.HospitalVisitExaminationReportsInfo;
import com.hutao.manage.pojo.CitizensInfo;
import com.hutao.manage.pojo.FirstLevelMedical;
import com.hutao.manage.pojo.HospNoteVersion;
import com.hutao.manage.pojo.HospitalNoteVersion;
import com.hutao.manage.pojo.HospitalizationNote;
import com.hutao.manage.pojo.MedicalBasicKey;
import com.hutao.manage.pojo.MedicalBasicTemplate;
import com.hutao.manage.pojo.MedicalResource;
import com.hutao.manage.pojo.MedicalResourcePic;
import com.hutao.manage.pojo.ScanFile;
import com.hutao.manage.pojo.TreatmentTrace;
import com.hutao.manage.pojo.UploadScan;
import com.hutao.manage.pojo.UploadScanFile;
import com.hutao.manage.util.DateUtil;
import com.hutao.manage.util.FileUtil;
import com.hutao.manage.util.HttpClientUtil;
import com.hutao.manage.util.JsonUtils;
import com.hutao.manage.util.MapUtil;
import com.hutao.manage.util.ObjectUtil;
import com.hutao.manage.util.Result;
import com.hutao.manage.util.StringUtil;

@Service
public class UploadFileService {
	
	@Autowired
	private MyConfig myConfig;

	@Autowired
	private UploadScanMapper uploadFileMapper;

	@Autowired
	private ScanFileMapper scanFileMapper;

	@Autowired
	private UploadScanFileMapper uploadScanFileMapper;

	@Autowired
	private UploadFileService uploadFileService;

	@Autowired
	private CitizensInfoMapper citizensInfoMapper;

	@Autowired
	private FirstLevelMedicalMapper firstLevelMedicalMapper;

	@Autowired
	private TreatmentTraceMapper treatmentTraceMapper;

	@Autowired
	private HospitalizationNoteMapper hospitalizationNoteMapper;

	@Autowired
	private MedicalResourceMapper medicalResourceMapper;

	@Autowired
	private MedicalResourcePicMapper medicalResourcePicMapper;

	@Autowired
	private HospitalNoteVersionMapper hospitalNoteVersionMapper;

	@Autowired
	private HospNoteBasicJsonMapper hospNoteBasicJsonMapper;
	
	@Autowired
	private BaseInfoMapper baseInfoMapper;
	
	@Autowired
	private CitizensInfoMapper patientMapper;
	
	@Autowired
	private HospNoteVersionMapper hospNoteVersionMapper;
	
	@Autowired
	private MedRecordService medRecordService;
	
	@Autowired
	private BasicInfoService basicInfoService;
	

	@TargetDataSource(name = "ds1")
	@Transactional(propagation = Propagation.REQUIRED)
	public int addUploadScan(UploadScan uploadScan) {

		return uploadFileMapper.insert(uploadScan);
	}

	@TargetDataSource(name = "ds1")
	@Transactional(propagation = Propagation.REQUIRED)
	public int addScanFile(ScanFile scanFile) {

		return scanFileMapper.insert(scanFile);
	}

	@TargetDataSource(name = "ds1")
	@Transactional(propagation = Propagation.REQUIRED)
	public int addUploadScanFile(UploadScanFile uploadScanFile) {

		return uploadScanFileMapper.insert(uploadScanFile);
	}

	@TargetDataSource(name = "ds1")
	@Transactional(propagation = Propagation.REQUIRED)
	public int uploadScanFiles(UploadScan uploadScan, List<ScanFile> scanFiles, List<UploadScanFile> uploadScanFiles) {
		uploadFileService.addUploadScan(uploadScan);
		for (ScanFile scanFile : scanFiles) {
			uploadFileService.addScanFile(scanFile);

		}
		for (UploadScanFile uploadScanFile : uploadScanFiles) {
			uploadScanFile.setUploadScanId(uploadScan.getId());
			uploadFileService.addUploadScanFile(uploadScanFile);
		}
		return 1;
	}
	
	public String verifyMedicalData(MedicalBasicTemplate medicalBasicTemplate) {
		//值验证出院入院日期,出院科室入院科室不能为空
		StringBuffer verifyMsg = new StringBuffer();
		if (StringUtils.isBlank(medicalBasicTemplate.getInHospitalDateTimeStr())) {
			verifyMsg.append("入院日期为空,");
		}
		
		if (StringUtils.isBlank(medicalBasicTemplate.getOutHospitalDateTimeStr())) {
			verifyMsg.append("出院日期为空,");
		}
		
		if (null == medicalBasicTemplate.getInDeptId()) {
			verifyMsg.append("入院科室为空,");
		}
		
		if (null == medicalBasicTemplate.getOutDeptId()) {
			verifyMsg.append("出院科室为空,");
		}
		
		if (StringUtils.isNotBlank(verifyMsg.toString())) {
			verifyMsg.append(medicalBasicTemplate.getMrId() + "-" + medicalBasicTemplate.getVisitNumber() + ",");
			verifyMsg.append("请联系信息科工作人员!");
		}
		
		return verifyMsg.toString();
	}
	
	@TargetDataSource(name = "ds1")
	@Transactional(propagation = Propagation.REQUIRED)
	public Result uploadScanFiles(List<UploadScan> uploadScans,String currentUser) {
		StringBuilder folderNames = new StringBuilder();
		StringBuilder verifyMedicalDataMsg = new StringBuilder();
		Map<String,String> visitGuids = new HashMap<String, String>();
		
		for (UploadScan uploadScan : uploadScans) {
			String folderName = uploadScan.getOriginalFolder();
			
			if(folderName != null){
				if(folderNames.length() > 0){
					folderNames.append("&");
				}
				folderNames.append("paramDatas="+folderName);
			}
		}
		
		//查询病案首页信息
		String userJson = HttpClientUtil.doGet(myConfig.getExportProjectUrl() + "export305/remote_query_patient_index?"+folderNames.toString());
		
		if(StringUtils.isNotBlank(userJson)){
			JSONObject userMap =JSONObject.parseObject(userJson);
			boolean success = userMap.getBoolean("success");
			
			if(success){
				List<Map<String, Object>> datas = (List<Map<String, Object>>)userMap.get("data");
				List<MedicalBasicTemplate> medicalBasicTemplateList = new ArrayList<MedicalBasicTemplate>(); 
				
				for (Map<String, Object> data : datas) {
					//visitGuid在这个方法里面生成
					MedicalBasicTemplate medicalBasicTemplate = MedicalBasicTemplate.getMedicalBasicTemplate(data);
					medicalBasicTemplate.setSexId(basicInfoService.getSexId(medicalBasicTemplate.getSexName()));
					medicalBasicTemplate.setInDeptId(basicInfoService.getInDeptId(medicalBasicTemplate.getInDeptCode()));
					medicalBasicTemplate.setOutDeptId(basicInfoService.getOutDeptId(medicalBasicTemplate.getOutDeptCode()));
					medicalBasicTemplate.setInHospitalTypeId(basicInfoService.getInHospitalTypeId(medicalBasicTemplate.getInHospitalTypeCode()));
					medicalBasicTemplate.setOutHospitalTypeId(basicInfoService.getOutHospitalTypeId(medicalBasicTemplate.getOutHospitalTypeCode()));
					
					//验证病案数据
					String verifyMsg = this.verifyMedicalData(medicalBasicTemplate);
					if (StringUtils.isNotBlank(verifyMsg)) {
						return new Result(false, verifyMsg, null, -2);
					}
					
					medicalBasicTemplateList.add(medicalBasicTemplate);
				}
				
				for (MedicalBasicTemplate medicalBasicTemplate : medicalBasicTemplateList) {
						List<String> queryVisitGuids = firstLevelMedicalMapper.getFirstGuidByMrIdAndVisitNumber(medicalBasicTemplate.getMrId(), medicalBasicTemplate.getVisitNumber());
						
						//已经上传过了
						if (!queryVisitGuids.isEmpty()) {
							visitGuids.put(medicalBasicTemplate.getMrId()+"-"+medicalBasicTemplate.getVisitNumber(), queryVisitGuids.get(0));
							continue;
						}
						
						CitizensInfo patient = CitizensInfo.getCitizensInfo(medicalBasicTemplate);
						FirstLevelMedical firstLevelMedical = FirstLevelMedical.getFirstLevelMedical(medicalBasicTemplate);
						HospitalizationNote note = HospitalizationNote.getHospitalizationNote(medicalBasicTemplate);
						//示踪记录 病案初始化,病案归档
						TreatmentTrace treatmentTrace = TreatmentTrace.getTreatmentTrace(medicalBasicTemplate.getVisitGuid(), currentUser);
						
						patientMapper.insert(patient);
						
						firstLevelMedicalMapper.insert(firstLevelMedical);
						
						//病案初始化
						treatmentTrace.setTraceTypeId(1);
						treatmentTraceMapper.insertSelective(treatmentTrace);
						
						//病案归档
						treatmentTrace.setTraceTypeId(2);
						treatmentTraceMapper.insertSelective(treatmentTrace);
						
						hospitalizationNoteMapper.insertSelective(note);
						
						firstLevelMedicalMapper.insertUploadVisitGuid(medicalBasicTemplate.getVisitGuid(), medicalBasicTemplate.getMrId(), medicalBasicTemplate.getVisitNumber());
						
						//本地写入json文件,数据库写入json文件
						Map medicalJsonDataMap = new HashMap();
						String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(medicalBasicTemplate.getVisitGuid());
						String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + medicalBasicTemplate.getVisitGuid() + "/";
						String fileName = medicalBasicTemplate.getVisitGuid() + ".json";
						String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";
						medicalJsonDataMap.put("userId", currentUser);
						medicalJsonDataMap.put("userName", currentUser);
						
						HospitalVisitExaminationReportsInfo examinationReportsInfo = new HospitalVisitExaminationReportsInfo();
						examinationReportsInfo.setVisitGuid(medicalBasicTemplate.getVisitGuid());
						//检验报告单
						medicalJsonDataMap.put("examinationReportsInfo", examinationReportsInfo);
						medicalJsonDataMap.put("firstGuid", medicalBasicTemplate.getVisitGuid());
						String jsonMapJson = JsonUtils.objectToJson(medicalJsonDataMap);
						
						try {
							//文件已经存在不需要在写入
							FileUtil.createOrEditFile(jsonMapJson, filePath, fileName);
							FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
						} catch (IOException e) {
							e.printStackTrace();
						}
						
						hospNoteBasicJsonMapper.insert(jsonMapJson);
						
						HospNoteVersion hospNoteVersion = new HospNoteVersion();
						hospNoteVersion.setCreateTime(new Date());
						hospNoteVersion.setFirstGuid(medicalBasicTemplate.getVisitGuid());
						hospNoteVersion.setFileName(versionFileName);
						hospNoteVersion.setOperator(currentUser);
						
						hospNoteVersionMapper.insert(hospNoteVersion);
						
						visitGuids.put(medicalBasicTemplate.getMrId()+"-"+medicalBasicTemplate.getVisitNumber(), medicalBasicTemplate.getVisitGuid());
				} // end
			} else {
				//远程抓取数据异常
				String msg = MapUtil.getStringTypeValueTrim(userMap, "stateMessage");
				return new Result(false, "远程抓取数据异常, 异常信息如下:" + msg, null, -4);
			}
		} else {
			return new Result(false, "medical-export服务没有启动");
		}
		
		
		for (UploadScan uploadScan : uploadScans) {
			String folderName = uploadScan.getOriginalFolder();
			String visitGuid = null;
			
			if(folderName != null){
				visitGuid = visitGuids.get(folderName);
			}
			
			uploadScan.setFirstLevelMedicalGuid(visitGuid);
			
			if (StringUtils.isBlank(visitGuid)) {
				continue;
			}
			
			uploadFileMapper.insert(uploadScan);
			
			for (ScanFile scanFile : uploadScan.getScanFiles()) {
				//判断是否已经有相关文件，有直接跳过
				if(medRecordService.medicalResourceIsExist(visitGuid, scanFile.getFileHash())){
					continue;
				}
				
				int count = scanFileMapper.getCountByFileHash(scanFile.getFileHash());
				if(count == 0){
					scanFileMapper.insert(scanFile);
				}
				
				UploadScanFile uploadScanFile=new UploadScanFile();
				uploadScanFile.setFileHash(scanFile.getFileHash());
				uploadScanFile.setOriginalFileName(scanFile.getOriginalName());
				uploadScanFile.setUploadScanId(uploadScan.getId());
				uploadScanFileMapper.insert(uploadScanFile);
				
				MedicalResource medicalResource=null;
				MedicalResourcePic medicalResourcePic=null;
				medicalResource=new MedicalResource();
				medicalResource.setFirstLevelMedicalId(visitGuid);
				medicalResource.setMedicalResourceTypeId(1);
				medicalResource.setCreateDate(new Date());
				medicalResourceMapper.insert(medicalResource);
				
				medicalResourcePic=new MedicalResourcePic();
				medicalResourcePic.setFileHash(scanFile.getFileHash());
				medicalResourcePic.setMedicalResourceId(medicalResource.getId());
				medicalResourcePicMapper.insert(medicalResourcePic);
			}
			
			TreatmentTrace treatmentTrace = new TreatmentTrace();
			treatmentTrace.setUserId(currentUser);
			String operator = treatmentTraceMapper.selectOperatorByGuidAndTreateCode(visitGuid, TreatmentTrace.VISIT_SCAN);
			
			if (StringUtils.isBlank(operator)) {
				List<Map<String,Object>> treatmentTyps = treatmentTraceMapper.getTreatmentTraceTypeByCode(TreatmentTrace.VISIT_SCAN);
				treatmentTrace.setTraceTypeId((Integer)treatmentTyps.get(0).get("id"));
				treatmentTrace.setTreatmentGuid(visitGuid);
				treatmentTraceMapper.insert(treatmentTrace);
			}
			
			
		}
		
		return new Result(true, "成功", null, 200);
	}

	@TargetDataSource(name = "ds1")
	@Transactional(propagation = Propagation.REQUIRED)
	public int uploadScanFileAndBindMedRecord(UploadScan uploadScan, List<ScanFile> scanFiles,
			List<UploadScanFile> uploadScanFiles, String firstGuid, String operator) {
		// 该病案为已上架记录历史版本
		if (firstLevelMedicalMapper.getPatientPutAwayByGuid(firstGuid) > 0) {
			HospitalNoteVersion hospitalNoteVersion = new HospitalNoteVersion();
			List<String> hospNoteBasicJsonList = hospNoteBasicJsonMapper
					.getHospBasicJsonByFirstGuid("\"" + firstGuid + "\"");
			List<String> fileUrlList = medicalResourceMapper.selectScanFileListByFirstGuid(firstGuid);
			HospitalNoteVersion oldHospitalNoteVersion = hospitalNoteVersionMapper
					.findHospitalNoteVersionByFirstGuid(firstGuid);

			if (null != hospNoteBasicJsonList && hospNoteBasicJsonList.size() > 0) {
				hospitalNoteVersion.setHospitlNoteJson(hospNoteBasicJsonList.get(0));
			}

			if (null == oldHospitalNoteVersion) {
				hospitalNoteVersion.setVersion(0);
			} else {
				hospitalNoteVersion.setVersion(oldHospitalNoteVersion.getVersion() + 1);
			}

			hospitalNoteVersion.setGuid(StringUtil.getId());
			hospitalNoteVersion.setPicUrlListJson(JsonUtils.objectToJson(fileUrlList));
			hospitalNoteVersion.setFirstGuid(firstGuid);
			hospitalNoteVersion.setOperator(operator);

			hospitalNoteVersionMapper.insertHospitalNoteVersion(hospitalNoteVersion);
		}

		int uploadNum = 0;
		uploadFileService.addUploadScan(uploadScan);
		for (ScanFile scanFile : scanFiles) {
			uploadFileService.addScanFile(scanFile);

		}
		for (UploadScanFile uploadScanFile : uploadScanFiles) {
			uploadScanFile.setUploadScanId(uploadScan.getId());
			uploadFileService.addUploadScanFile(uploadScanFile);
			MedicalResource medicalResource = new MedicalResource();
			medicalResource.setFirstLevelMedicalId(firstGuid);
			medicalResource.setMedicalResourceTypeId(1);
			medicalResource.setCreateDate(new Date());
			medicalResourceMapper.insert(medicalResource);

			MedicalResourcePic medicalResourcePic = new MedicalResourcePic();
			medicalResourcePic.setFileHash(uploadScanFile.getFileHash());
			medicalResourcePic.setMedicalResourceId(medicalResource.getId());
			medicalResourcePicMapper.insert(medicalResourcePic);
			uploadNum++;
		}

		return uploadNum;
	}

/*	public static void main(String[] args) {
		List<String> list = null;
		String str = JsonUtils.objectToJson(list);
	}*/

	@TargetDataSource(name = "ds1")
	@Transactional(propagation = Propagation.REQUIRED)
	public int uploadScanFilesOfPatient(UploadScan uploadScan, List<ScanFile> scanFiles,
			List<UploadScanFile> uploadScanFiles, CitizensInfo citizensInfo, FirstLevelMedical firstLevel,
			HospitalizationNote hospitalizationNote) {

		citizensInfo.setGuid(StringUtil.getId());
		citizensInfoMapper.insert(citizensInfo);

		firstLevel.setGuid(StringUtil.getId());
		firstLevel.setCreateDate(new Date());
		firstLevel.setCitizensGuid(citizensInfo.getGuid());
		firstLevel.setStatus(1);
		firstLevelMedicalMapper.insert(firstLevel);

		TreatmentTrace treatmentTrace = new TreatmentTrace();
		treatmentTrace.setUserId(uploadScan.getCreateUserId());
		treatmentTrace.setTraceTypeId(1);
		treatmentTrace.setTreatmentGuid(firstLevel.getGuid());
		treatmentTraceMapper.insert(treatmentTrace);
		hospitalizationNote.setFirstLevelMedicalGuid(firstLevel.getGuid());
		hospitalizationNoteMapper.insert(hospitalizationNote);
		uploadScan.setFirstLevelMedicalGuid(firstLevel.getGuid());
		uploadFileService.addUploadScan(uploadScan);
		for (ScanFile scanFile : scanFiles) {
			uploadFileService.addScanFile(scanFile);

		}
		for (UploadScanFile uploadScanFile : uploadScanFiles) {
			uploadScanFile.setUploadScanId(uploadScan.getId());
			uploadFileService.addUploadScanFile(uploadScanFile);
			MedicalResource medicalResource = new MedicalResource();
			medicalResource.setFirstLevelMedicalId(firstLevel.getGuid());
			medicalResource.setMedicalResourceTypeId(1);
			medicalResource.setCreateDate(new Date());
			medicalResourceMapper.insert(medicalResource);

			MedicalResourcePic medicalResourcePic = new MedicalResourcePic();
			medicalResourcePic.setFileHash(uploadScanFile.getFileHash());
			medicalResourcePic.setMedicalResourceId(medicalResource.getId());
			medicalResourcePicMapper.insert(medicalResourcePic);
		}

		treatmentTrace = new TreatmentTrace();
		treatmentTrace.setUserId(uploadScan.getCreateUserId());
		treatmentTrace.setTraceTypeId(2);
		treatmentTrace.setTreatmentGuid(firstLevel.getGuid());
		treatmentTraceMapper.insert(treatmentTrace);

		return 1;
	}

	@TargetDataSource(name = "ds1")
	@Transactional(propagation = Propagation.REQUIRED)
	public int uploadScanImgs(UploadScan uploadScan, List<ScanFile> scanFiles, List<UploadScanFile> uploadScanFiles) {

		uploadFileService.addUploadScan(uploadScan);
		for (ScanFile scanFile : scanFiles) {
			uploadFileService.addScanFile(scanFile);

		}
		for (UploadScanFile uploadScanFile : uploadScanFiles) {
			uploadScanFile.setUploadScanId(uploadScan.getId());
			uploadFileService.addUploadScanFile(uploadScanFile);
			MedicalResource medicalResource = new MedicalResource();
			medicalResource.setFirstLevelMedicalId(uploadScan.getFirstLevelMedicalGuid());
			medicalResource.setMedicalResourceTypeId(1);
			medicalResource.setCreateDate(new Date());
			medicalResourceMapper.insert(medicalResource);

			MedicalResourcePic medicalResourcePic = new MedicalResourcePic();
			medicalResourcePic.setFileHash(uploadScanFile.getFileHash());
			medicalResourcePic.setMedicalResourceId(medicalResource.getId());
			medicalResourcePicMapper.insert(medicalResourcePic);
		}

		return 1;
	}
	
	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	public int removeMedImage(String firstGuid, String fileHash) {
		MedicalResourcePic medicalResourcePic = medicalResourcePicMapper.selectByFirstGuidAndFileHash(firstGuid, fileHash);
	    medicalResourcePicMapper.deleteByPrimaryKey(medicalResourcePic.getId());
		medicalResourceMapper.deleteByPrimaryKey(medicalResourcePic.getMedicalResourceId());
		return 1;
	}
	
	@TargetDataSource(name="ds1")
	public List<Map<String,Object>> getUploadVisitGuid(){
		return firstLevelMedicalMapper.getUploadVisitGuid();
	}

}
